package com.techblor.library.wechat.api.officialaccount;

import com.alibaba.fastjson.JSON;
import com.techblor.library.wechat.beans.token.AccessToken;
import com.techblor.library.wechat.utils.HttpClientUtil;
import com.techblor.library.wechat.utils.StringUtil;

import static com.techblor.library.wechat.constants.WechatConstant.BASE_URL;

/**
 * 获取token
 *
 * @author zhangceven
 */
public class TokenApi {

    /**
     * 获取access_token
     * 在从Token获取access_token前
     * 先判断是否包含errcode信息
     * 如果没有,就可以Token中获取access_token
     * 否则,就从BaseResult获取返回的错误信息
     *
     * @param appId
     * @param appSecret
     * @return
     */
    public static AccessToken getAccessToken(String appId, String appSecret) {
        if(StringUtil.isBlank(appId)){
            throw new RuntimeException("appid不能为空");
        }

        if(StringUtil.isBlank(appSecret)){
            throw new RuntimeException("secret不能为空");
        }

        String url = BASE_URL + "/cgi-bin/token?grant_type=client_credential&appid=" + appId +
                "&secret=" + appSecret;

        String result = HttpClientUtil.doGet(url);
        return JSON.parseObject(result, AccessToken.class);
    }

}
